﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spanner
{
    internal interface IHasBaseName
    {
        string BaseName { get; set; }
    }

    internal class Namer
    {
        internal int NewNameCounter = 1;

        internal string NewNamePrefix = "x";

        internal HashSet<string> UsedNames = new HashSet<string> { };

        internal Dictionary<IHasBaseName, string> ItemToName = new Dictionary<IHasBaseName, string> { };

        internal string UniqueifyAndRegisterName(string name)
        {
            if (!string.IsNullOrEmpty(name) && !UsedNames.Contains(name))
            {
                UsedNames.Add(name);
                return name;
            }

            var prefix = (string.IsNullOrEmpty(name) ? NewNamePrefix : name);

            var newName = (string) null;
            do
            {
                newName = prefix + NewNameCounter++;
            } while (UsedNames.Contains(newName));

            UsedNames.Add(newName);

            return newName;
        }

        internal string Name(IHasBaseName x)
        {
            var name = (string) null;
            if (ItemToName.TryGetValue(x, out name)) return name;

            name = UniqueifyAndRegisterName(x.BaseName);

            ItemToName[x] = name;

            return name;
        }
    }
}
